package initialize

import (
	_ "github.com/go-sql-driver/mysql"
	"go-study/global"
	"go-study/initialize/internal"
	"go-study/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"os"
)

func Gorm() *gorm.DB {
	mysqlConfig := mysql.Config{
		DSN:                       "root:xiodi.cn123@tcp(192.168.11.207:3306)/go-study?charset=utf8mb4&parseTime=True&loc=Local",
		DefaultStringSize:         191,
		SkipInitializeWithVersion: false,
	}
	if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Config()); err != nil {
		return nil
	} else {
		db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
		sqlDb, _ := db.DB()
		sqlDb.SetMaxIdleConns(10)
		sqlDb.SetMaxOpenConns(100)
		return db
	}
}

func RegisterTables() {
	db := global.ASW_DB
	err := db.AutoMigrate(
		model.User{},
	)
	if err != nil {
		log.Println("auto migrate user failed")
		os.Exit(0)
	}
}
